package com.pingan.haofang.searchcloud.common.validator;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * 参数校验处理器工厂
 *
 * @author BAOJIE371
 * @date 2017/2/20
 * @since 1.0.0
 */
public final class ValidHandlerFactory {

    private static final Map<String, ValidHandlerBean> HANDLER_MAP = new HashMap<>();

    /**
     * 注册validHandler，须确保handlerName全局唯一
     *
     * @param handlerName
     * @param bean
     * @param method
     */
    public synchronized static void addHandler(String handlerName, Object bean, Method method) {
        Objects.requireNonNull(handlerName, "handlername is null");
        Objects.requireNonNull(bean, "bean is null");
        Objects.requireNonNull(method, "method is null");
        String key = formatKey(handlerName, bean.getClass());
        HANDLER_MAP.put(key, ValidHandlerBean.of(bean, method));
    }

    /**
     * 根据handlerName获取handler
     *
     * @param handlerName
     * @param clazz
     * @return
     */
    public static Optional<ValidHandlerBean> getHandler(String handlerName, Class<?> clazz) {
        String key = formatKey(handlerName, clazz);
        return Optional.ofNullable(HANDLER_MAP.get(key));
    }

    private static String formatKey(String handlerName, Class<?> clazz) {
        return String.format("%s-%s", handlerName, clazz.getName());
    }
}
